<!--
 * @Author: Bennty
 * @Date: 2024-08-27 11:05:55
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2024-11-04 10:35:06
 * @Description: 请填写简介
-->
<template>
    <el-dialog v-model="props.visible" title="编辑辅材" @close="handleClose" width="30%" destroy-on-close>
        <el-form :model="formData" ref="addFormRef" label-width="auto">
            <el-form-item label="材料大类" prop="productCategoriesType" label-position="right">
                <el-select v-model="selectedCatagory" value-key="id" placeholder="请选择">
                    <el-option v-for="item in props.types" :key="item.id" :label="item.majorName" :value="item"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="材料小类" prop="productSubcategoryType" label-position="right">
                <el-select v-model="selectedSubCategory" value-key="id" placeholder="请选择">
                    <el-option v-for="item in singleCategoryList" :key="item.id"  :label="item.subclassName" :value="item"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="具体规格" prop="specsDetail" label-position="right">
                <el-input v-model="formData.specsDetail" placeholder="请输入"></el-input>
            </el-form-item>
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="单价" prop="price" label-position="right">
                        <el-input v-model="formData.price" type="number" placeholder="请输入"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="包装工费" prop="packagingLaborCost" label-position="right">
                        <el-input type="number" v-model="formData.packagingLaborCost" placeholder="请输入"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-form-item label="最低库存" prop="lowInventory" label-position="right">
                <el-input v-model.number="formData.lowInventory" placeholder="请输入"></el-input>
            </el-form-item>
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="现有库存" prop="currentInventory" label-position="right">
                        <el-input v-model.number="formData.currentInventory" placeholder="请输入"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="单位" prop="unite" label-position="right">
                        <el-input v-model="formData.unit" placeholder="请输入"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="采购冻结" prop="purchaseFreezeInventory" label-position="right">
                        <el-input v-model.number="formData.purchaseFreezeInventory" placeholder="请输入"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="生产冻结" prop="productFreezeInventory" label-position="right">
                        <el-input v-model="formData.productFreezeInventory" placeholder="请输入"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-form-item label="图片上传" prop="image" label-position="right">
                <el-upload
                        class="upload-demo"
                        ref="uploadRef"
                        drag
                        :action="uploadImgUrl"
                        :headers="headers"
                        v-model:file-list="fileList"
                        :before-upload="beforeUpload"
                        :auto-upload="true"
                        :limit="1"
                        :on-exceed="handleExceed"
                    >
                        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                        <div class="el-upload__text">
                        将文件拖入此处或<em>点击这里上传</em>
                        </div>
                        <template #tip>
                            <div class="el-upload__tip">
                                jpg/png 文件不得超过 5MB
                            </div>
                        </template>
                    </el-upload>
            </el-form-item>
            <el-form-item prop="status" label-position="right">
                <el-switch
                    v-model="formData.status"
                    class="ml-2"
                    active-value="1"
                    inactive-value="0"
                    style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949; margin-right: 10px"
                />
                <span v-if="formData.status == '1'" :style="{color:'#13ce66'}">启用</span>
                <span v-else :style="{color:'#ff4949'}">停用</span>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button  type="primary" @click="handleSubmit">确 定</el-button>
                <el-button @click="handleClose">取 消</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import type { FormInstance, UploadInstance, UploadProps,UploadUserFile,UploadRawFile } from 'element-plus';
import { genFileId } from 'element-plus'
import { globalHeaders } from "@/utils/request";
import { getSingleByTotalApi } from '@/api/sj/warehouse/typeManagement';
import { updateAuxiliaryApi } from '@/api/sj/warehouse/auxiliary';

const props = defineProps(['visible','types','data']);
const emits = defineEmits(['close', 'submit']);
const addFormRef = ref<FormInstance>();
const uploadRef = ref<UploadInstance>();
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadImgUrl = ref(baseUrl + "/resource/oss/upload");
const headers = ref(globalHeaders);
const singleCategoryList = ref<any[]>([]);
const selectedCatagory = ref<any>({});
const selectedSubCategory = ref<any>({});
const fileList = ref<UploadUserFile[]>([]);

const formData = ref({
    productCategoriesType: undefined,
    productSubcategoryType: undefined,
    specsDetail: undefined,
    price: undefined,
    packagingLaborCost: undefined,
    lowInventory: undefined,
    currentInventory: undefined,
    unit: undefined,
    purchaseFreezeInventory: undefined,
    productFreezeInventory: undefined,
    imageUrl: undefined,
    remark: undefined,
    status: '1',
    type: 2
});

/** 根据大类获取小类 */
const getSingleCatagory = async (type: string) => {
    const { data } = await getSingleByTotalApi(type,'');
    singleCategoryList.value = data;
    return data;
};

watch(()=>selectedCatagory, (newData)=>{
    if(newData.value?.majorType){
        getSingleCatagory(newData.value.majorType);
    }
},{deep: true});

watch(()=>[props.data, props.visible],([newData, newVisible])=>{
    formData.value = newData;
    fileList.value = [{name: 'image1',url: newData.imageUrl}];
    const majorType = props.types.filter((type:any)=>type.majorType == newData.productCategoriesType)[0];
    selectedCatagory.value = majorType;
    if(newVisible){
        getSingleCatagory(newData.productCategoriesType).then((result)=>{
            const subType = result.filter((type:any)=>type.subclassType == newData.productSubcategoryType)[0];
            selectedSubCategory.value = subType;
        });
    }
    
});

const handleSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    console.log(uploadFile);
    const file = uploadFile;
    uploadRef.value!.clearFiles();
    file.uid = genFileId();
    
    //@ts-ignore
    // formData.value.image = URL.createObjectURL(uploadFile.raw!);

};

const beforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('图片格式与要求不符')
        return false
    } else if (rawFile.size / 1024 / 1024 > 5) {
        ElMessage.error('图片不可超过 5MB!')
        return false
    }
    return true
};

const handleExceed: UploadProps['onExceed'] = (files) => {
    uploadRef.value!.clearFiles();
    const file = files[0] as UploadRawFile;
    file.uid = genFileId();
    uploadRef.value!.handleStart(file);
    uploadRef.value!.submit();
};

const handleSubmit = async () => {
    // console.log(fileList.value[0]);
    const submitData = {
        ...formData.value,
        //@ts-ignore
        imageUrl: fileList.value[0]?.response?.data?.url || fileList.value[0].url,
        productCategoriesType: selectedCatagory.value.majorType,
        productCategoriesName: selectedCatagory.value.majorName,
        productSubcategoryType: selectedSubCategory.value.subclassType,
        productSubcategoryName: selectedSubCategory.value.subclassName
    };
    // console.log(submitData);
    const { code } = await updateAuxiliaryApi(submitData);
    if(code == 200){
        emits('submit', true);
        handleClose();
    }else{
        emits('submit', false);
    }
};

const handleClose = ()=>{
    emits('close');
    addFormRef.value?.resetFields();
    uploadRef.value?.clearFiles();
    selectedCatagory.value = undefined;
    selectedSubCategory.value = undefined;
};
</script>

<style lang="scss" scoped>
.dialog-footer{
    display: flex;
    justify-content: center;
}
</style>

